package com.begye.smartloan.apptest.renzheng.bangka

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtRenZhengBangKaBinding
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.adapter.RenZhengBangKaAdapter
import com.begye.smartloan.apptest.renzheng.alldone.RenZhengAllDoneActivity
import com.begye.smartloan.apptest.renzheng.dialog.FillItemBangKaDeleteDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemBangKaListDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemBangKaNeedMoreDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemBangKaSameChannelDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemBangKaSubmitDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemEmptyFillDialogFragment
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.renzheng.views.FillItemDoingHeader
import com.begye.smartloan.apptest.renzheng.views.FillItemStatus
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.gongong.SysConfigViewModel
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import org.json.JSONObject


@SuppressLint("CustomWelcomeScreen")
class RenZhengBangKaActivity : AppCompatActivity() {

    private lateinit var _binding: AtRenZhengBangKaBinding
    private lateinit var _fillItemBangKaListDialogFragment: FillItemBangKaListDialogFragment
    private lateinit var _fillItemBangKaDeleteDialogFragment: FillItemBangKaDeleteDialogFragment
    private lateinit var _fillItemBangKaNeedMoreDialogFragment: FillItemBangKaNeedMoreDialogFragment
    private lateinit var _fillItemEmptyFillDialogFragment: FillItemEmptyFillDialogFragment
    private lateinit var _fillItemBangKaSubmitDialogFragment: FillItemBangKaSubmitDialogFragment
    private lateinit var _fillItemBangKaSameChannelDialogFragment: FillItemBangKaSameChannelDialogFragment
    private lateinit var _renZhengBangKaAdapter: RenZhengBangKaAdapter

    private val _renZhengViewModel by lazy {
        ViewModelProvider(this)[RenZhengBangKaViewModel::class.java]
    }

    private val _sysConfigViewModel by lazy {
        ViewModelProvider(this)[SysConfigViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtRenZhengBangKaBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoneFillLiveData.observe(this) {
            addDoneUI(it)
        }

        _yongHuLiuChengViewModel.onDoingBangKaFillLiveData.observe(this) {
            addDoingUI(it)
            _renZhengViewModel.requestBangKaList()
        }

        _yongHuLiuChengViewModel.onFutureFillLiveData.observe(this) {
            addFutureUI(it)
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = RenZhengAllDoneActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP,
                    params = hashMapOf<String, String>().apply {
                        put("titles", it)
                    }
                )
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

        _renZhengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _sysConfigViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _renZhengViewModel.onBangKaListLiveData.observe(this) {
            it?.let {
                _renZhengBangKaAdapter.dataList = it
                _renZhengBangKaAdapter.notifyDataSetChanged()
            }
        }

        _renZhengViewModel.onNeedBangKaSameChannelLiveData.observe(this) {
            it?.let { result ->
                _fillItemBangKaSameChannelDialogFragment.addDataSource(result)
                _fillItemBangKaSameChannelDialogFragment.addClickListener { _, params ->
                    _renZhengViewModel.requestSaveBangKa(params)
                }
                _fillItemBangKaSameChannelDialogFragment.showNow(
                    supportFragmentManager,
                    "sameChannel"
                )
            }
        }
    }

    private fun configUIEvent() {

        _binding.atRenZhengNav.initConfig(
            text = getString(R.string.fill_text_3),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                if (LoginTool.filterAdType()) {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.atRenZhengDoingSubmit.setOnClickListener {
            if (_renZhengViewModel.hasNoBangKaItems()) {
                _fillItemEmptyFillDialogFragment.showNow(supportFragmentManager, "emptyFIll")

            } else if (_renZhengViewModel.hasLessThan2BangKaItems()) {
                _fillItemBangKaNeedMoreDialogFragment.showNow(supportFragmentManager, "needMore")

            } else {
                _fillItemBangKaSubmitDialogFragment.addClickListener {
                    _yongHuLiuChengViewModel.requestYongHuLiuChengForBangKa()
                }
                _fillItemBangKaSubmitDialogFragment.addDataSource(_renZhengViewModel.currentBangKaList())
                _fillItemBangKaSubmitDialogFragment.showNow(supportFragmentManager, "submit")
            }
        }

        _renZhengBangKaAdapter = RenZhengBangKaAdapter(emptyList()) { position, item, isAdd ->
            if (isAdd) {
                // show add dialog
                _binding.atRenZhengDoingAdd.performClick()
            } else {
                // delete
                _fillItemBangKaDeleteDialogFragment.addDataSource(item)
                _fillItemBangKaDeleteDialogFragment.addClickListener { _, jsonObject ->
                    _renZhengViewModel.requestDeleteBangKa(jsonObject.optString("id", ""))
                }
                _fillItemBangKaDeleteDialogFragment.showNow(supportFragmentManager, "del")
            }
        }
        _binding.atRenZhengDoingList.layoutManager = LinearLayoutManager(this)
        _binding.atRenZhengDoingList.adapter = _renZhengBangKaAdapter

        _fillItemEmptyFillDialogFragment = FillItemEmptyFillDialogFragment()
        _fillItemBangKaSubmitDialogFragment = FillItemBangKaSubmitDialogFragment()
        _fillItemBangKaDeleteDialogFragment = FillItemBangKaDeleteDialogFragment()
        _fillItemBangKaNeedMoreDialogFragment = FillItemBangKaNeedMoreDialogFragment()
        _fillItemBangKaSameChannelDialogFragment = FillItemBangKaSameChannelDialogFragment()

        _fillItemBangKaListDialogFragment = FillItemBangKaListDialogFragment()
        _fillItemBangKaListDialogFragment.addTitle(getString(R.string.fill_text_18))

        _binding.atRenZhengDoingAdd.setOnClickListener {
            val channels = SysConfigTool.filterBangKaChannels()
            _fillItemBangKaListDialogFragment.addDataSource(channels)
            _fillItemBangKaListDialogFragment.addClickListener { _, jsonObject ->
                _renZhengViewModel.requestSaveBangKa(jsonObject)
            }
            _fillItemBangKaListDialogFragment.showNow(
                supportFragmentManager,
                FillItemBangKaListDialogFragment::class.java.simpleName
            )
        }

        val channels = SysConfigTool.filterBangKaChannels()
        if (channels.length() == 0) {
            _sysConfigViewModel.requestSystemConfiguration()
        }
    }

    private fun configUIData() {
        _yongHuLiuChengViewModel.requestYongHuLiuChengForBangKa()
    }

    private fun addDoneUI(value: List<JSONObject>? = null) {
        _binding.atRenZhengDoneContent.removeAllViews()

        value?.let { list ->
            for (index in list.indices) {
                val item = list[index]
                val fillItem = FillItemStatus(this)
                fillItem.initDataSource(item)
                fillItem.addCompleted(true)
                _binding.atRenZhengDoneContent.addView(fillItem)
            }
        }
    }

    private fun addDoingUI(obj: JSONObject? = null) {
        obj?.let { result ->
            val fillItemDoingHeader = FillItemDoingHeader(this)
            fillItemDoingHeader.hideContent(false)
            fillItemDoingHeader.addTag(result.optString("tag", ""))
            fillItemDoingHeader.addTitle(result.optString("title", ""))
            _binding.atRenZhengDoingContent.addView(fillItemDoingHeader)
        }
    }

    private fun addFutureUI(value: List<JSONObject>? = null) {
        _binding.atRenZhengFutureContent.removeAllViews()

        value?.let { list ->
            for (index in list.indices) {
                val item = list[index]
                val fillItem = FillItemStatus(this)
                fillItem.initDataSource(item)
                fillItem.addCompleted(false)
                _binding.atRenZhengFutureContent.addView(fillItem)
            }
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

